package com.restaurant.springboot.service.impl;


import com.restaurant.springboot.entity.CommentEntity;
import com.restaurant.springboot.entity.OrderEntity;
import com.restaurant.springboot.entity.dto.CommentDTO;
import com.restaurant.springboot.repositories.CommentRepository;
import com.restaurant.springboot.repositories.OrderRepository;
import com.restaurant.springboot.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    OrderRepository orderRepository;

    @Override
    public List<Map<String, Object>> findAll(Pageable page) {
        return commentRepository.getAllUserComments(page);
    }

    @Override
    public Map<String, Object> getCommentById(Integer id) {
        return commentRepository.getUserCommentById(id);
    }

    @Override
    @Transient
    public boolean insertComment(CommentDTO commentDTO) {
        if(commentRepository.save(commentDTOToPO(commentDTO))!=null){
            Optional<OrderEntity> byId = orderRepository.findById(commentDTO.getOrderId());
            if(byId.isPresent()){
                OrderEntity orderEntity = byId.get();
                orderEntity.setState(4);
                orderRepository.save(orderEntity);
            }
            return true;
        }
        return false;
    }

    private CommentEntity commentDTOToPO(CommentDTO commentDTO){
        return new CommentEntity(commentDTO.getUserId(), commentDTO.getContent(), commentDTO.getOrderId(),0,new Timestamp(System.currentTimeMillis()));
    }

    @Override
    @Transient
    public void deleteComment(Integer id) {
        commentRepository.deleteById(id);
    }

    @Override
    @Transient
    public void praise(Integer commentId) {
        CommentEntity comment = commentRepository.findById(commentId).get();
        comment.setPraise(comment.getPraise()+1);
        commentRepository.save(comment);
    }

    @Override
    public boolean isExistsComment(int orderId) {
        return commentRepository.existsByOrderId(orderId);
    }


}
